'use strict';

const controller = require('egg').Controller;

class MainController extends controller {
  async checkLogin() {
    // 登录校验
    const { ctx } = this;
    const userName = ctx.request.body.userName;
    const password = ctx.request.body.password;
    const sql = " SELECT userName FROM admin_user WHERE userName = '" + userName +
      "' AND password = '" + password + "'";

    const result = await this.app.mysql.query(sql);
    if (result.length > 0) {
      const openId = new Date().getTime();
      ctx.session.openId = { openId };
      ctx.body = {
        data: '登录成功',
        openId,
      };
    } else {
      ctx.body = {
        data: '登录失败',
      };
    }
  }

  async getTypeInfo() {
    // 获取文章类别
    const { ctx } = this;
    const result = await this.app.mysql.select('type');
    ctx.body = {
      data: result,
    };
  }

  async addArticle() {
    // 添加文章
    const { ctx } = this;
    const articleData = this.ctx.request.body;

    const result = await this.app.mysql.insert('article', articleData);
    const insertSuccess = result.affectedRows === 1;
    const insertId = result.insertId;
    ctx.body = {
      insertSuccess,
      insertId,
    };
  }

  async updateArticle() {
    // 修改文章
    const { ctx } = this;
    const articleData = this.ctx.request.body;

    const result = await this.app.mysql.update('article', articleData);
    const updateSuccess = result.affectedRows === 1;
    ctx.body = {
      updateSuccess,
    };
  }

  async getArticleList() {
    // 获取文章列表
    const { ctx } = this;
    const sql = 'SELECT article.id as id,' +
      'article.title as title,' +
      'article.introduce as introduce,' +
      'article.addTime  as addTime,' +
      'article.view_count as view_count ,' +
      'type.typeName as typeName ' +
      'FROM article LEFT JOIN type ON article.type_id = type.Id ' +
      'ORDER BY article.id DESC ';

    const result = await this.app.mysql.query(sql);
    ctx.body = {
      list: result,
    };
  }

  async delArticle() {
    // 删除文章
    const { ctx } = this;
    const result = await this.app.mysql.delete('article', { id: ctx.params.id });

    const delSuccess = result.affectedRows === 1;

    ctx.body = { delSuccess };
  }

  // 根据文章ID得到文章详情，用于修改文章
  async getArticleById() {
    const { ctx } = this;

    const sql = 'SELECT article.id as id,' +
      'article.title as title,' +
      'article.introduce as introduce,' +
      'article.article_content as article_content,' +
      'article.addTime as addTime,' +
      'article.view_count as view_count ,' +
      'type.typeName as typeName ,' +
      'type.id as typeId ' +
      'FROM article LEFT JOIN type ON article.type_id = type.Id ' +
      'WHERE article.id=' + ctx.params.id;

    const result = await this.app.mysql.query(sql);

    this.ctx.body = { data: result };
  }
}

module.exports = MainController;
